namespace Brjnk.GpxExplorer.Workspace.GCBrowser
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows.Threading;
    using Brjnk.Common;

    /// <summary>
    /// </summary>
    public abstract class Browser : INotifyPropertyChanged
    {
        public abstract BrowserTab OpenNewTab(Uri uri, bool focusTab);

        public abstract BrowserTab OpenNewTab(bool focus);

        public abstract BrowserTab OpenHomeTab();

        public Browser()
        {
            tabs.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(tabs_CollectionChanged);
            if (tabs.Count == 0) OpenHomeTab();
            CreateCommands();
        }

        private void tabs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (tabs.Count == 0)
            {
                DispatcherTimer tmr = new DispatcherTimer() { Interval = TimeSpan.FromTicks(1) };
                tmr.Tick += new EventHandler((a, b) => { OpenHomeTab(); tmr.Stop(); });
                tmr.Start();
            }
        }

        private ObservableCollection<BrowserTab> tabs = new ObservableCollection<BrowserTab>();

        public ObservableCollection<BrowserTab> Tabs
        {
            get { return tabs; }
            private set { tabs = value; OnPropertyChanged("Tabs"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public GenericCommand AddTabCommand { get; private set; }

        protected virtual void CreateCommands()
        {
            AddTabCommand = new GenericCommand(o => OpenNewTab(true));
        }
    }
}